package com.oa.server.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.oa.server.entity.Menu;
import com.oa.server.entity.MenuRole;
import com.oa.server.entity.Role;
import com.oa.server.result.ResponseBean;
import com.oa.server.service.IMenuRoleService;
import com.oa.server.service.IMenuService;
import com.oa.server.service.IRoleService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 权限组
 */
@RestController
@RequestMapping("/system/basic/permiss")
public class PermissionController {
    @Autowired
    private IMenuService menuService;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IMenuRoleService menuRoleService;
    @ApiOperation(value="获取所有角色")
    @GetMapping("/role/getAllRoles")
    public List<Role> getAllRoles(){
        return roleService.list();
    }

    @ApiOperation(value = "添加角色")
    @PostMapping("/role/addRole")
    public ResponseBean addRole(@RequestBody Role role){
        if(!role.getName().startsWith("ROLE_")){
            role.setName("ROLE_"+role.getName());
        }
        if(roleService.save(role)){
            return ResponseBean.success("添加角色成功");
        }
        return ResponseBean.error("添加失败");
    }
    @ApiOperation(value="删除角色")
    @DeleteMapping("/role/deleteRole/{roleId}")
    public ResponseBean deleteRoleById(@PathVariable Integer rid){
        if(roleService.removeById(rid)){
            return ResponseBean.success("删除成功");
        }
        return ResponseBean.error("删除失败");
    }

    @ApiOperation(value = "访问所有菜单")
    @GetMapping("/getAllMenus")
    public List<Menu> getAllMenus(){
        return menuService.getAllMenus();
    }

    @ApiOperation(value = "根据角色id查询菜单id")
    @GetMapping("/getMenuIdByRoleId/{roleId}")
    public List<Integer> getMidById(@PathVariable Integer roleId){
        return menuRoleService.list(new QueryWrapper<MenuRole>().eq("rid",roleId)).stream().map(MenuRole::getMid)
                .collect(Collectors.toList());
    }

    @ApiOperation(value = "更新角色菜单")
    @PutMapping("/updateMenuRole")
    public ResponseBean updateMenuRole(Integer rid,Integer[] mids){
        return menuRoleService.updateMenuRole(rid,mids);
    }


}

